﻿using System.Collections.Generic;

namespace YPBox
{
    public static class ListExtension
    {
        /// <summary>
        /// 随机1个元素
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list"></param>
        /// <returns></returns>
        public static T Random<T>(this IList<T> list)
        {
            if (list == null || list.Count <= 0)
            {
                return default;
            }
            int index = RandomHelper.RInt(0, list.Count);
            return list[index];
        }

        /// <summary>
        /// 获取列表随机N个元素
        /// </summary>
        public static List<T> RandomN<T>(this List<T> list, int count)
        {
            if (list == null || count >= list.Count)
                return list;
            List<T> tempList = new List<T>();
            tempList.AddRange(list);
            tempList.SortRandom<T>();
            return tempList.GetRange(0, count);
        }

        public static int RandomByWeight(this List<int> list)
        {
            // 计算总权重
            int totalWeight = 0;
            foreach (var item in list)
                totalWeight += item;

            // 产生随机数
            int randomValue = RandomHelper.RInt(0, totalWeight);
            int currentMinWeight = 0;
            for (int i = 0; i < list.Count; i++)
            {
                if (currentMinWeight <= randomValue && randomValue < currentMinWeight + list[i])
                {
                    return i;
                }
                currentMinWeight += list[i];
            }

            // 如果遍历完仍未找到，返回默认值
            return 0;
        }


        /// <summary>
        /// 乱序排序列表
        /// </summary>
        public static List<T> SortRandom<T>(this List<T> list)
        {
            if (list == null || list.Count <= 1)
                return list;
            int randomIndex;
            for (int i = list.Count - 1; i > 0; i--)
            {
                randomIndex = RandomHelper.RInt(0, i);
                T temp = list[i];
                list[i] = list[randomIndex];
                list[randomIndex] = temp;
            }
            return list;
        }
    }
}